package com.atguigu.tingshu.album.api;

import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.common.result.Result;
import io.minio.*;
import io.minio.errors.*;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Tag(name = "上传管理接口")
@RestController
@RequestMapping("api/album")
public class FileUploadApiController {

    @Autowired
    private MinioConstantProperties minioConstantProperties;


    @PostMapping("fileUpload")
    public Result<String> fileUpload(MultipartFile file){

        try {
            //初始化MinIOClient
            MinioClient minioClient = MinioClient.builder().endpoint(minioConstantProperties
                            .getEndpointUrl())
                    .credentials(minioConstantProperties.getAccessKey(), minioConstantProperties.getSecreKey())
                    .build();

            //判断筒是否存在
            boolean flag = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
            //不存在则创建桶
            if (!flag){
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
            }

            //文件上传
            //生成文件名字
            String fileName = UUID.randomUUID().toString()+file.getName()+"."+ FilenameUtils.getExtension(file.getOriginalFilename());
            minioClient.putObject(PutObjectArgs.builder().bucket(minioConstantProperties.getBucketName()).object(fileName).stream(file.getInputStream(),file.getSize(),-1).contentType(file.getContentType()).build());

            return Result.ok(minioConstantProperties.getEndpointUrl()+"/"+minioConstantProperties.getBucketName()+"/"+fileName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

}
